package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
public  abstract class PictureUploadTemp {

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;


    // 模板方法
    // 模板方法 定义上传流程
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) throws IOException {
        //1，校验图片
        validPicture(inputSource);
        //2.图片上传地址
//        String uuid= RandomUtil.randomString(16);
//        String originalFileName = getOriginalFileName(inputSource);
//        String uploadFileName=String.format("%s/%s.%s", DateUtil.formatDate(new Date()),uuid, FileUtil.getSuffix(originalFileName));
//        String uploadPath=String.format("%s/%s",uploadPathPrefix,uploadFileName);
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFileName(inputSource);
        // 自己拼接文件上传路径，而不是使用原始文件名称，可以增强安全性
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);


        File file=null;
        //3.创建临时文件
        try {
            file=File.createTempFile(uploadPath, null);

            //处理临时文件
            processFile(inputSource,file);
            //4.上传图片到对象存储
            // 4.上传图片到对象存储（使用支持图片信息获取的方法）
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);

            //获取到缩率图
            // 4.上传图片到对象存储（使用支持图片信息获取的方法）
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                CIObject ciObject = objectList.get(0);
//                CIObject thumbnailObject = objectList.get(1);

                //有生成缩略图，才得到缩略图
                CIObject thumbnailObject = ciObject;


                if(objectList.size()>1){
                    thumbnailObject = objectList.get(1);
                }

                return buildResult(originalFilename,ciObject,thumbnailObject,imageInfo);


            }

            //5.封装返回结果
            return  buildResult(originalFilename,file,uploadPath,imageInfo);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //6.清理临时文件
            deleteTempFile(file);
        }




    }

    private UploadPictureResult buildResult(String originalFilename, CIObject compressedObject, CIObject thumbnailObject,ImageInfo imageInfo) {


        UploadPictureResult uploadPictureResult=new UploadPictureResult();
        int picWidth = compressedObject.getWidth();
        int picHeight = compressedObject.getHeight();
        double picScale=(double) picWidth/picHeight;
        uploadPictureResult.setPicName(originalFilename);
        uploadPictureResult.setPicSize(compressedObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedObject.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        //设置图片缩略图
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost()+"/"+thumbnailObject.getKey());



        //设置图片压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+compressedObject.getKey());
        return uploadPictureResult;
    }

//    private UploadPictureResult buildResult(String originalFilename, CIObject compressedObject) {
//
//    }
//    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
//        // 1. 校验图片
//        validPicture(inputSource);
//        // 2. 图片上传地址
//        String uuid = RandomUtil.randomString(16);
//        String originalFilename = getOriginalFileName(inputSource);
//        // 自己拼接文件上传路径，而不是使用原始文件名称，可以增强安全性
//        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
//                FileUtil.getSuffix(originalFilename));
//        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
//        File file = null;
//        try {
//            // 3. 创建临时文件，获取文件到服务器
//            file = File.createTempFile(uploadPath, null);
//            // 处理文件来源
//            processFile(inputSource, file);
//            // 4. 上传图片到对象存储
//            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
//            // 5. 获取图片信息对象，封装返回结果
//            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//            // 获取到图片处理结果
//            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
//            List<CIObject> objectList = processResults.getObjectList();
//
//            return buildResult(originalFilename, file, uploadPath, imageInfo);
//        } catch (Exception e) {
//            log.error("图片上传到对象存储失败", e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
//        } finally {
//            // 6. 临时文件清理
//            this.deleteTempFile(file);
//        }
//
//    }


    //校验输入源(本地文件或URL)
    protected abstract void validPicture(Object inputSource);

    //获取输入源的原始文件地址
   protected abstract String getOriginalFileName(Object inputSource);

   //获取输入源的临时文件
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    //封装返回结果
    private UploadPictureResult buildResult(String originalFileName, File file, String uploadFilePath, ImageInfo imageInfo) {

        UploadPictureResult uploadPictureResult=new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = (double) picWidth / picHeight;
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFileName));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());


        return uploadPictureResult;
    }


    //删除临时文件
    private void deleteTempFile(File file) {
        if (file == null){
            return;
        }
        boolean delete = file.delete();
        if (!delete){
            log.error("file delete error{}",file.getAbsolutePath());
        }
    }
}
